﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Blazing.BusinessObjects.Tagging;
using Blazing.BusinessObjects.Queries;
using System.BusinessObjects.With;

namespace Blazing.WebFacade
{
    public class UrlFragmentParser
    {
        public class SearchUrlItem
        {
            public string Fragment;
            public TaxonomyTag Tag;
        }

        public List<SearchUrlItem> OrderedTags { get; private set; }
        public List<TaxonomyTag> OrderedTaxonomyTags
        {
            get
            {
                return (List<TaxonomyTag>)With.Each(OrderedTags).Item<SearchUrlItem,TaxonomyTag>(delegate(SearchUrlItem item){ return item.Tag; });
            }
        }

        public UrlFragmentParser(string urlFragments)
        {
            OrderedTags = new List<SearchUrlItem>();
            IList<string> tagFragments = new List<string>();
            try
            {
                string[] fragments = urlFragments.Split('/');

                foreach (string str in fragments)
                {
                    if (!string.IsNullOrEmpty(str))
                        tagFragments.Add(str);
                }

                IList<TaxonomyTag> tags = TaxonomyTag.Search(QrySearchTaxonomyTagsBySlugs.Query(tagFragments));

                foreach (TaxonomyTag tag in tags)
                {
                    OrderedTags.Add(new SearchUrlItem
                    {
                        Fragment = tag.Slug,
                        Tag = tag
                    });
                }
            }
            catch { }
        }

        public static string GenerateUrl(string urlBase, List<TaxonomyTag> tagsInUrl, TaxonomyTag exclude)
        {
            tagsInUrl.SortTags();

            string url = urlBase;
            foreach (TaxonomyTag t in tagsInUrl)
            {
                if (exclude == null || (exclude != null && t.ID != exclude.ID))
                    url += t.Slug + "/";
            }

            return UrlHelper.CheckUrl(url);
        }
    }
}
